package com.example.movie_demo

import android.app.Service
import android.content.Intent
import android.media.AudioAttributes
import android.media.AudioManager
import android.media.SoundPool
import android.os.Binder
import android.os.IBinder
import android.util.Log
import android.media.MediaPlayer




class MusicService : Service() {

    private lateinit var sp: SoundPool
    private var bgStreamId: Int? = null
    private var backGroundSoundData = mutableMapOf<Int, Int>()
    private var effectSoundData = mutableMapOf<Int, Int>()

    private lateinit var completeCallBack: OnLoadCompleteListener
    var loadFinished = false

    fun setOnLoadCompleteListener(callback: OnLoadCompleteListener) {
        this.completeCallBack = callback
    }


    override fun onCreate() {
        sp = SoundPool.Builder()
            .setMaxStreams(10)
            .setAudioAttributes(
                AudioAttributes.Builder().setLegacyStreamType(AudioManager.STREAM_MUSIC).build()
            )
            .build()
        backGroundSoundData[0] = sp.load(this, R.raw.gotechgo, 1)
        backGroundSoundData[1] = sp.load(this, R.raw.mario, 1)
        backGroundSoundData[2] = sp.load(this, R.raw.tetris, 1)
        effectSoundData[0] = sp.load(this, R.raw.clapping, 1)
        effectSoundData[1] = sp.load(this, R.raw.cheering, 1)
        effectSoundData[2] = sp.load(this, R.raw.lestgohokies, 1)


        sp.setOnLoadCompleteListener { soundPool, sampleId, status ->
            loadFinished = true
            this.completeCallBack.complete()
        }



    }


    override fun onBind(intent: Intent): IBinder {
        Log.e("music Service", "onBind: ready to play music")
        return MyBinder()
    }


    inner class MyBinder : Binder() {


        fun playBgMusic(index: Int) {
            if (bgStreamId != null) {
                sp.stop(bgStreamId!!)
            }
            bgStreamId = sp.play(backGroundSoundData[index]!!, 1f, 1f, 1, 1, 1f)
        }

        fun playEffectMusic(index: Int) {
            sp.play(effectSoundData[index]!!, 1f, 1f, 1, 1, 1f)
        }

        fun pause() {
            sp.pause(bgStreamId!!)
        }

        fun restart(index: Int) {
            sp.stop(bgStreamId!!)
            bgStreamId = sp.play(backGroundSoundData[index]!!, 1f, 1f, 1, 1, 1f)
        }

        fun resume() {
            sp.resume(bgStreamId!!)
        }

        fun getService(): MusicService {
            return this@MusicService
        }

    }
}